﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.JCI.Common.Entity;
using Microsoft.JCI.Bll;
using Microsoft.JCI.Common.Utility;
using System.Data;
using Telerik.WebControls;

namespace Microsoft.JCI.Portal.SysManage
{
    public partial class UserAdd : BasePage
    {
        public Guid UserID
        {
            get
            {
                if (ViewState["UserID"] == null) return Guid.Empty;
                else return new Guid(ViewState["UserID"].ToString());
            }
            set { ViewState["UserID"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitForm();

                if (Request.QueryString["UserID"] != null)
                {
                    UserID = new Guid(Request.QueryString["UserID"]);
                    SetFormData();
                }
 
            }
        }

        private void InitForm()
        {   
            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = new SqlDbParameter();
            parm.ColumnName = "Deleted";
            parm.ColumnType = DbType.Byte;
            parm.ParameterName = "@Deleted";
            parm.ParameterValue = 0;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            SystemBll bll = new SystemBll();
            cblRoles.DataSource = bll.GetAll<SysRoleEntity>(parms);
            cblRoles.DataTextField = "RoleName";
            cblRoles.DataValueField = "RoleID";
            cblRoles.DataBind();

            //DataTable dt = bll.QueryCompanyEntity(new List<SqlDbParameter>());
            //ddCompany.DataSource = dt;
            //ddCompany.DataTextField = "Name";
            //ddCompany.DataValueField = "CompanyCode";
            //ddCompany.DataBind();

            DataTable dt1 = bll.QueryCompanyEntity(new List<SqlDbParameter>());
            MCompany.DataSource = dt1;
            MCompany.DataTextField = "Name";
            MCompany.DataValueField = "CompanyCode";
            MCompany.DataBind();
            MCompany.Text = "";
        }
        private void SetFormData()
        {
            if (UserID != Guid.Empty)
            {
                SysUserEntity entity = null;//
                SystemBll bll = new SystemBll();
                entity = bll.Get<SysUserEntity>(UserID);

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = entity.UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                entity.UserRoleRelationList = bll.GetAll<SysUserRoleRelationEntity>(parms);

                txtAccount.Text = entity.Account;
                txtUserName.Text = entity.UserName;
                txtEmail.Text = entity.Email;
                foreach (ListItem item in cblRoles.Items)
                { 
                    Predicate<SysUserRoleRelationEntity> predicate = 
                        delegate(SysUserRoleRelationEntity ent)
                        {
                            if(ent.RoleID == new Guid(item.Value))return true;
                            return false;
                        };
                    bool IsExists = entity.UserRoleRelationList.Exists(predicate);
                    if (IsExists)
                        item.Selected = true;
                }

                //ddCompany.SelectedValue = entity.CompanyCode;

                string[] arrCompany = {};
                if (entity.CompanyCode != string.Empty)
                {
                    arrCompany = entity.CompanyCode.Split(',');
                }

                foreach (RadComboBoxItem item in MCompany.Items)
                {
                    CheckBox checkBox = (CheckBox)item.FindControl("CheckBox");
                    HiddenField hiden = (HiddenField)item.FindControl("MV");
                    for (int i = 0; i < arrCompany.Length; i++)
                    {
                        if (arrCompany[i] == hiden.Value)
                        {
                            checkBox.Checked = true;
                        }
                    }
                }
            }
        }

        private string GetCompanyCode
        {
            get
            {
                string CompanyCode = string.Empty;
                foreach (RadComboBoxItem item in MCompany.Items)
                {
                    CheckBox checkBox = (CheckBox)item.FindControl("CheckBox");
                    HiddenField hiden = (HiddenField)item.FindControl("MV");
                    if (checkBox.Checked)
                    {
                        CompanyCode += hiden.Value + ",";
                    }
                }
                return CompanyCode;
            }
        }
        
        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandcloseerror", "alert('" + Message + "');", true);
            }
            else
            ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                UserID = Guid.Empty;
                txtAccount.Text = "";
                txtUserName.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool Save(ref string Message)
        {
             
            SystemBll systemBll = new SystemBll();
            SysUserEntity entity = null;

            //检查Account是否存在
            SystemBll bll = new SystemBll();
            List<SysUserEntity> entityList= new List<SysUserEntity>();
            if (UserID == Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }
            else 
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.NotEqual;
                parms.Add(parm);

                parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }

            //try save user info
            if (UserID != Guid.Empty)
            {
                entity = bll.Get<SysUserEntity>(UserID);
            }
            else
            {
                entity = new SysUserEntity();
                UserID = entity.UserID;
                entity.Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5");
                entity.CreatedBy = entity.LastModifyBy = CurrentUserEntity.Account;
                entity.CreatedOn = entity.LastModifyOn = DateTime.Now;
            }

            entity.UserName = txtUserName.Text;
            entity.Account = txtAccount.Text.Trim();
            entity.LastModifyOn = DateTime.Now;
            entity.LastModifyBy = string.Empty;
            entity.Email = txtEmail.Text.Trim();



            entity.CompanyCode = GetCompanyCode;
            //保存权限     
            List<SysUserRoleRelationEntity> UserRoleList = new List<SysUserRoleRelationEntity>();
            SysUserRoleRelationEntity UserRoleEntity = null;
            foreach (ListItem item in cblRoles.Items)
            {
                if (item.Selected)
                {
                    UserRoleEntity = new SysUserRoleRelationEntity();
                    UserRoleEntity.RoleID = new Guid(item.Value);
                    UserRoleEntity.UserID = UserID;
                    UserRoleEntity.Deleted = false;
                    UserRoleList.Add(UserRoleEntity);
                }
            }

            entity.UserRoleRelationList = UserRoleList;
 

            systemBll.SaveUser(entity);
            return true;
        }

        protected void lnkbtnUpdate_Click(object sender, EventArgs e)
        {
            SystemBll systemBll = new SystemBll();
            SysUserEntity entity = null;
            //检查Account是否存在
            SystemBll bll = new SystemBll();
            int count = bll.Count<SysUserEntity>("and Account='" + txtAccount.Text.Trim() + "'");

            if (count > 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('该账户重复，请核对后再进行修改操作！');", true);
                return;
            }

            ////try save user info
            //if (UserID != Guid.Empty)
            //{
            //    entity = bll.Get<SysUserEntity>(UserID);
            //}
            else
            {
                entity = new SysUserEntity();
                entity = bll.Get<SysUserEntity>("and UserID='" + UserID + "'");
                entity.UserID = UserID;
                entity.UserName = txtUserName.Text;
                entity.Account = txtAccount.Text.Trim();
                entity.LastModifyOn = DateTime.Now;
                entity.LastModifyBy = CurrentUserEntity.UserName;
                entity.Email = txtEmail.Text.Trim();
                entity.CompanyCode = GetCompanyCode;
                //删除原来的权限
                systemBll.Delete<SysUserRoleRelationEntity>("and UserID = '" + UserID + "'");
                //保存权限     
                List<SysUserRoleRelationEntity> UserRoleList = new List<SysUserRoleRelationEntity>();
                SysUserRoleRelationEntity UserRoleEntity = null;
                foreach (ListItem item in cblRoles.Items)
                {
                    if (item.Selected)
                    {
                        UserRoleEntity = new SysUserRoleRelationEntity();
                        UserRoleEntity.RoleID = new Guid(item.Value);
                        UserRoleEntity.UserID = UserID;
                        UserRoleEntity.Deleted = false;
                        UserRoleList.Add(UserRoleEntity);
                    }
                }
                entity.UserRoleRelationList = UserRoleList;
                //更新用户信息
                systemBll.Update(entity);

                //插入权限表
                bll.SavePower(entity);

                ClientScript.RegisterStartupScript(this.GetType(), "updateandclose", "window.close();", true);

            }
        }

   

    }
}
